const express = require("express");
const cors = require("cors");
const db = require("../libs/DBHelper");
const file = require("../libs/fileHelper")
const proxy = require('http-proxy-middleware');//服务器代理中间件 解决跨域
const md5 = require("md5");


let server = express();
//配置静态资源
server.use(express.static("../../src"));
//配置中间件
//post能够快速使用 body
server.use(express.urlencoded({ extended: false }));
server.use(express.json());

server.use(cors());//配置跨域
console.log(proxy);

//服务器代理
server.use('/search', proxy.createProxyMiddleware({
    // 服务器api地址目录 
    target: 'https://you.163.com/xhr/search/searchAutoComplete.json',
    changeOrigin: true,
    pathRewrite: {
        "^/search": ""
    }
}));

server.get("/index", function (request, response) {
    console.log(2222222);
    response.end("hi...");
})

server.post("/account/login", async (request, response) => {
    //1.接受前端的数据 (用户名和密码)
    let { user, pwd } = request.body;
    //2. 准备sql语句
    let sql = "SELECT `uId`,`uUser`,`uPhone` FROM `userinfo` WHERE `uUser`=? AND upwd=? AND ustatus=1;";
    let parmas = [
        user,
        md5(md5(pwd) + "cs2104")
    ]

    try {
        let result = await db.exec(sql, parmas);
      
        if (result && result.length >= 1) {
            response.json({
                msg: "登录成功!",
                data: result,
                code: 200
            })
        } else {
            response.json({
                msg: "登录失败!",
                code: 200
            })
        }

    } catch (error) {
        response.json({
            msg: "登录失败!",
            err: error,
            code: -200
        })
    }
})


server.post("/account/reg", async function (request, response) {
    //1.接受参数 
    let { name, pwd,  tel } = request.body;
    //2.准备sql语句
    let sql = "INSERT INTO `userinfo` (`uUser`,`uPwd`,`uPhone`)VALUES(?,?,?);";
    //参数
    //md5的2次加密
    let parmas = [name, md5(md5(pwd) + "cs2104"), tel];

    try {
        let result = await db.exec(sql, parmas);
        //注意:除了查询返回的是数组,
        //其他 (插入,修改,删除)返回的 受影响行数
        //不是undefined并且受影响行数大于等于1
        let isReg = result && result.affectedRows;
        response.json({
            msg: isReg ? "注册成功!" : '注册失败!',
            code: 200,
            
        })
    } catch (error) {
        response.json({
            msg: '注册失败!',
            err: error,
            code: -200
        })
    }
})


//获取所有的产品信息
server.get("/api/prodList", async (request, response) => {

    var data = JSON.parse((await file.getData("../data/production.json")) || '[]');
    response.json({
        msg: "查询成功",
        data,
        code: 200
    })
})
// http://127.0.0.1:8080/api/prodList/1127007
// http://127.0.0.1:8080/api/prodList/549481605917

//  Vue也有这样的语法  /:id 对应的params.id  
// 只能get请求

server.get("/api/prodList/:id", async (request, response) => {

    let id = request.params.id

    var dataList = JSON.parse((await file.getData("../data/production.json")) || '[]');

    let data = dataList.find(item => item.pId == id);
    response.json({
        msg: "查询成功",
        data,
        code: 200
    })
})

//加入购物车 
//get--> query
//post-->body
// /:id -->parmas.id
server.post("/api/addCart", async (request, response) => {
    let { uId, pId, pName, pPirce, pNumer, pImg } = request.body;

    //1.去数据库中查询一下,是否购买过
    let sql = "SELECT * FROM `carts` WHERE `uId`=? AND`pId`=? AND `cStatus`=1;";
    let parms = [uId, pId];
    let isAddCart = (await db.exec(sql, parms)).length >= 1;// 为true 已购买
    if (isAddCart) {
        //修改数量和金额
        let sql_Update = "UPDATE `carts` SET `cNum`=cNum+? ,`cTotal`=cNum*`cPrice` WHERE `uId`=? AND`pId`=? AND `cStatus`=1;";
        let params_Update = [pNumer, uId, pId];

        let isUpdate = (await db.exec(sql_Update, params_Update)).affectedRows >= 1;
        response.json({
            msg: isUpdate ? "加入购物车成功!u" : "加入购物车失败!u",
        })

    } else {
        //插入一条新的购买记录
        let sql_insert = "INSERT INTO `carts` (`uId`,`pId`,`cName`,`cImg`,`cNum`,`cPrice`,`cTotal`)VALUES(?,?,?,?,?,?,?);"

        let params_insert = [uId, pId, pName, pImg, pNumer, pPirce, pNumer * pPirce];

        let isInsert = (await db.exec(sql_insert, params_insert)).affectedRows >= 1;
        response.json({
            msg: isInsert ? "加入购物车成功!i" : "加入购物车失败!i",
        });

    }
})




//设置端口
server.listen(8080, () => {
    console.log("服务启动完毕!");
})